<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use EasyWeChat\Work\GroupRobot\Messages\Markdown;
use Illuminate\Http\Request;
use Symfony\Component\Cache\Adapter\RedisAdapter;

class QyWebhookController extends Controller
{

    protected $app;
    public function __construct()
    {
        $this->app = \EasyWeChat\Factory::work(config('wechat.work.default'));
        // 创建缓存实例
        $cache = new RedisAdapter(app('redis')->connection()->client());
        // 替换应用中的缓存
        $this->app->rebind('cache', $cache);
    }

    /**
     * Git提交发送企业微信消息
     *
     * @param Request $request
     * @return void
     */
    public function git(Request $request)
    {

        $dataJson = $request->getContent();
        $dataArr = json_decode($dataJson, true);
        if (!empty($dataArr)) {

            // 只处理git push
            if ($dataArr['event_name'] == 'push') {
                $userName = $dataArr['user_name'];
                $projectName = $dataArr['project']['name'];
                $commits = [];
                foreach($dataArr['commits'] as $commit) {
                    $commits[] = $commit['message'];
                }

                $commits = rtrim(implode('\n', $commits), '\n');
                $submitTime = Carbon::parse($dataArr['commits'][0]['timestamp'])->toDateTimeString();
		// 逆糖科技 webhooks
		//$groupKey = '30c484fb-0f65-4c3f-bd55-284d45b418a5';
		// 数治科技 webhooks
		$groupKey = 'b185d588-5e86-4fa6-8317-38a6a3266c59';
                $messenger = $this->app->group_robot_messenger;
                $content = "## <font color=\"warning\">{$userName}</font>提交了代码
                    > 项目：{$projectName}
                    > 时间：{$submitTime}
                    > 内容：{$commits}
                ";

                $markdown = new Markdown($content);
                $messenger->message($markdown)->toGroup($groupKey)->send();
                echo "Success";
            } else {
                echo "Wating";
            }
        }
    }
}
